<template>
  <div class="roles">
    <!-- 面包屑区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>角色管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片区域 -->
    <el-card>
      <!-- 添加角色 -->
      <el-button class="addbtn" type="primary" @click="addRolesVisible = true">角色添加</el-button>

      <!-- 表单区域 -->
      <!-- <el-table :data="rolesList" row-key="id" border stripe :tree-props="{}"> -->
      <el-table :data="rolesList" border stripe >
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row :class="['row',index==0?'rowtop':'','vertical']" v-for="(item,index) in scope.row.children" :key="item.id">
              <!-- 第一列 -->
              <el-col :span="5" class="ddd">
                <el-tag type="success" closable disable-transitions>{{item.authName}} </el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>

              
              <el-col :span="19">
                <template>
                  <el-row v-for="(it,ind) in item.children" :class="[ind !== 0 ? 'rowtop':null,'vertical']" :key="it.id">
                   <!-- 第二列 --> 
                  <el-col :span="5">
                    <el-tag type="success" closable disable-transitions>{{it.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>

                  <!-- 第三列 -->
                  <el-col :span="19" >
                      <el-tag type="warning" v-for="its in it.children" :key="its.id" closable disable-transitions>{{its.authName}}</el-tag>
                  </el-col>
                </el-row>
                </template>
                
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column type="index" label="#"> </el-table-column>
        <el-table-column prop="roleName" label="角色名称"> </el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"> </el-table-column>

        <el-table-column label="操作" width="380">
          <!-- 作用域插槽 -->
          <template slot-scope="scope">

            <!-- 编辑 -->
            <el-button type="success" icon="el-icon-edit" size="small" @click="editRole(scope.row.id)">编辑</el-button>

            <!-- 删除 -->
            <el-button type="danger" icon="el-icon-delete" size="small" @click="delRole(scope.row.id)" >删除</el-button>

            <!-- 分配权限 -->
            <el-button type="warning" icon="el-icon-search" size="small"  @click="shareRole(scope.row)" >分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加角色对话框 -->
    <el-dialog
      title="添加角色"
      :visible.sync="addRolesVisible"
      :before-close="handleClose"
    >
      <el-form :model="rolesInfo" ref="addRolesRef" :rules="addRolesRules">
        <el-form-item
          label="角色名称"
          :label-width="formLabelWidth"
          prop="roleName"
        >
          <el-input v-model="rolesInfo.roleName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item
          label="角色描述"
          :label-width="formLabelWidth"
          prop="roleDesc"
        >
          <el-input v-model="rolesInfo.roleDesc" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="quitAddRoles('addRolesRef')">取 消</el-button>
        <el-button type="primary" @click="addRoles('addRolesRef')"
          >确 定</el-button
        >
      </div>
    </el-dialog>

    <!-- 编辑对话框 -->

    <el-dialog title="修改角色" :visible.sync="editRolesVisible" :before-close="handleClose1">
      <el-form :model="editRoleInfo" ref="editRoleRef" :rules="editRolesRules">
        <el-form-item label="角色名称" :label-width="formLabelWidth" prop="roleName">
          <el-input v-model="editRoleInfo.roleName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" :label-width="formLabelWidth" prop="roleDesc">
          <el-input v-model="editRoleInfo.roleDesc" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="quitEdit('editRoleRef')">取 消</el-button>
        <el-button type="primary" @click="sureEdit('editRoleRef')">确 定</el-button>
      </div>
    </el-dialog>


    <!-- 删除对话框 使用的弹框 MessageBox 没用对话框-->

    <!-- 分享角色权限对话框 -->
    <el-dialog title="收货地址" :visible.sync="shareRolesVisible">
      <el-tree :data="rolesTree" show-checkbox :props="defaultProps" 
      default-expand-all
      :default-checked-keys="arr"
  node-key="id"
  ref="rolestree"
  highlight-current>
      </el-tree>
      <div slot="footer" class="dialog-footer">
        <el-button @click="shareRolesVisible = false">取 消</el-button>
        <el-button type="primary" @click="sureShare('rolestree')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      rolesList: [],
      rolesTree:[],
      defaultProps: {
          children: 'children',
          label: 'authName'
        },
        arr:[],
      addRolesVisible: false,
      editRolesVisible:false,
      shareRolesVisible:false,
      formLabelWidth: "80px",
      // 添加角色
      rolesInfo: {
        roleName: "",
        roleDesc: "",
      },
      // 添加角色校验
      addRolesRules: {
        roleName: [{ required: true, message: "角色名称不能为空" }],
      },
      // 编辑角色
      editRoleInfo: {
        roleId:'',
        roleName: "",
        roleDesc: "",
      },
      editRolesRules:{
        roleName:[{ required: true, message: "角色名称不能为空" }],
        roleDesc:[{ required: true, message: "角色描述不能为空" }]
      },
      shareRoleInfo:{
        roleId:'',
        rids:''
      },
    };
  },
  created() {
    this.getRolesList();
  },
  methods: {
    // 获取角色列表数据
    async getRolesList() {
      const { data: res } = await this.$http.get("roles");
      // console.log(res.data);
      if (res.meta.status !== 200)
        return this.$message.error("获取角色列表失败");
      this.rolesList = res.data;
    },
    // 编辑角色 点击编辑按钮打开编辑角色对话框
    async editRole(id) {
      this.editRolesVisible = true;
      const {data:res} = await this.$http.get(`roles/${id}`);
      if(res.meta.status !== 200) return
      // console.log(res.data);
      for(var key in this.editRoleInfo) {
        this.editRoleInfo[key] = res.data[key];
      }
    },
    // 添加角色 -- x 关闭按钮
    handleClose() {
      this.quitAddRoles("addRolesRef");
    },
    // 添加角色 -- 取消
    quitAddRoles(refname) {
      this.$refs[refname].resetFields();
      this.addRolesVisible = false;
    },
    // 添加角色 -- 确定
    addRoles(refname) {
      this.$refs[refname].validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.$http.post("roles", this.rolesInfo);
        if (res.meta.status !== 201) return this.$message.error("添加角色失败~~~");
        this.quitAddRoles('addRolesRef');
        this.getRolesList();
        this.$message.success("成功添加角色!!!");
      });
    },
    // -----------------------------
    // 编辑角色 -- 确定按钮
    sureEdit(refname) {
      this.$refs[refname].validate(async valid => {
        if(!valid) return
        const {data:res} = await this.$http.put(`roles/${this.editRoleInfo.roleId}`,this.editRoleInfo);
        if(res.meta.status !== 200) return
        this.editRolesVisible = false;
        this.getRolesList();
        this.$message.success('成功修改角色!!!');
      })
    },
    // 编辑角色 --- x 关闭按钮
    handleClose1() {
      this.quitEdit('editRoleRef');
    },
    // 编辑角色 --- 取消按钮
    quitEdit(refname) {
      this.$refs[refname].resetFields();
      this.editRolesVisible = false;
    },
    // 删除角色
    async delRole(id) {
      const result = await this.$confirm('此操作将永久删除该角色，是否继续?','提示',{
        confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
      }).catch(err => err);
      // console.log(result);
      if(result !== 'confirm') return
      const {data:res} = await this.$http.delete(`roles/${id}`);
      if(res.meta.status !== 200) return this.$message.error('删除角色失败~~~');
      this.getRolesList();
      this.$message.success('成功删除角色~~~');
    },
    // 分配角色权限
    async shareRole(rowInfo) {
      this.shareRoleInfo.roleId = rowInfo.id;
      const {data:res} = await this.$http.get('rights/tree');
      this.rolesTree = res.data;
      // const result = this.rolesList.find(item => item.id == id);

      this.arr = [];
      this.getKeys(rowInfo,this.arr);
      this.shareRolesVisible = true;
      // rowInfo.forEach(item => {
        // item.children.forEach(its => {
        //   its.children.forEach(it => {
        //     this.arr.push(it.id);
        //   })
          
        // })
        
      // })  
    },
    // 递归
    getKeys(node,arr) {
      if(!node.children) {
        return arr.push(node.id);
      }
      node.children.forEach(item => this.getKeys(item,this.arr))
    },
    // 分享角色 -- 确定按钮
    async sureShare(refname) {
      const ids1  = this.$refs[refname].getHalfCheckedKeys();
      const ids2 = this.$refs[refname].getCheckedKeys();
      this.shareRoleInfo.rids = [...ids1,...ids2].toString();
      
      const {data:res} = await this.$http.post(`roles/${this.shareRoleInfo.roleId}/rights`,this.shareRoleInfo);
      if(res.meta.status !== 200) return this.$message.error('数据加载失败')
      this.shareRolesVisible = false;
      this.getRolesList();
      this.$message.success('分配权限成功!!!');
    }
  },
};
</script>

<style scoped>
.el-card {
  min-width: 730px;
}
.addbtn[data-v-1dd2e2da]{
  margin-bottom: 15px;
}
.vertical{
  display: flex;
  align-items: center;
}
.el-table .row {
  border-bottom: 1px solid #ccc;
}
.el-table .rowtop {
  border-top: 1px solid #ccc;
}
.el-table .el-tag {
  margin: 10px 8px 10px 0;
}
</style>>
